#ifndef __SESSION_HPP__
#define __SESSION_HPP__

#include <boost/thread.hpp>

#include "protocol.h"
#include "luoo_session_base.hpp"
#include "luoo_mysql_database.hpp"

class session : public luoo::session_base<session>
{
private:
	typedef session_base<session> base_type;

public:
	session(boost::asio::io_service& ios, base_type::session_manager_type& manager)
		: base_type(ios, manager)
	{}

	virtual ~session()
	{}

public:
	virtual void handle_start()
	{
		get_socket().set_option(boost::asio::socket_base::keep_alive(true));
		get_socket().set_option(boost::asio::socket_base::send_buffer_size(5 * 1024 * 1024));
		get_socket().set_option(boost::asio::socket_base::receive_buffer_size(5 * 1024 * 1024));

//		printf("%s connected! tid:[%X]\n", get_socket().remote_endpoint().address().to_string().c_str(), boost::this_thread::get_id());
	}

	virtual void handle_recv(luoo::packet_header* packet_ptr, luoo::uint32 packet_len)
	{
//		printf("%s message![%d]\n", get_socket().remote_endpoint().address().to_string().c_str(), get_session_id());
//		std::cout << get_socket().remote_endpoint().address().to_string() << "[" << get_session_id() << "]" << " message" << std::endl;;
		recv_packet_cnt_++;
		switch (packet_ptr->get_packet_id())
		{
		case kMSGIDX_REQ_LOGIN:
			{
				ReqLogin* packet = reinterpret_cast<ReqLogin*>(packet_ptr);
				std::cout << packet->id << " - " << packet->pwd << std::endl;
				sMySQLDB.async_query("select * from user_info", boost::bind(&session::HandleQuery, shared_from_this(), _1));
			}
			break;
		default:
			break;
		}
	}
	
	virtual void handle_close()
	{
		std::cout << get_socket().remote_endpoint().address().to_string() << " disconnected" << std::endl;;
	}

private:
	void HandleQuery(luoo::mysql_record_set& record_set)
	{
		if (record_set.is_successed())
		{
			std::string name;
			std::string pwd;
			std::string mail;
			int user_qq;
			for (unsigned int i = 0; i < record_set.get_num_rows(); ++i)
			{
				record_set[i] >> name >> pwd >> mail >> user_qq;
			}

			RepLogin msg;
			msg.result = true;
			SendNetMsg(&msg, sizeof(msg));

	//		printf("%s login scessed![%d]\n", get_socket().remote_endpoint().address().to_string().c_str(), get_session_id());
		}
		else
		{
			std::cout << record_set.get_error() << std::endl;
		}
	}

private:
	void SendNetMsg(luoo::packet_base* packet_ptr, luoo::uint16 packet_length)
	{
	//	packet_ptr->encode();
		send_packet_cnt_++;
		send(packet_ptr, packet_length);
	}

private:
	luoo::uint32 send_packet_cnt_;
	luoo::uint32 recv_packet_cnt_;
};

#endif//__SESSION_HPP__